package com.distributer.order.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.distributer.order.controller.dto.OrderReqInfo;
import com.distributer.order.controller.dto.OrderRspInfo;
import com.distributer.order.model.Order;
import com.distributer.order.service.OrderService;

@RestController
@RequestMapping("/")
public class OrderCommandController {

	@Autowired
	private OrderService orderService;
	
	@RequestMapping(value="/order",method=RequestMethod.POST)
	@ResponseBody
	public OrderRspInfo addOrder(OrderReqInfo orderReqInfo){
		String orderNo = orderService.addOrder(orderReqInfo);
		//同步获取结果。
		//自旋200毫秒，如果200毫秒内拿到结果，则告知前段最终创建的结果。
		//否则提供订单编号供前端进行轮询。
		int waitTime = 0;
		while (true) {
			if (waitTime > 200) {
				break;
			}
			Order orderFromDb = orderService.findOrderByOrderNo(orderNo);
			if (orderFromDb.statusIsVisible()) {
				//返回成功结果并更新最新的数据到缓存。
				orderService.refreshOrderToCache(orderFromDb);
				return new OrderRspInfo(orderFromDb.getOrderNo(), orderFromDb.getOrderStatus()+"", "Y");
			}
			try {
				Thread.sleep(20);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		return new OrderRspInfo(orderNo, null , "N");
	}
}
